package wassalt.client;

import wassalt.Utils.AppConstants;
import wassalt.Utils.DbAdapter;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;

import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class FavoriteNotificationsActivity extends ListActivity implements
		OnClickListener {

	DbAdapter db;
	public ListAdapter la;
	public ListView lv;
	Cursor c;
	Button done;
	Button cancel;

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.favorites);
		setTitle(getString(R.string.favorites));

		// Configure the buttons
		done = (Button) this.findViewById(R.id.favorites_done);
		cancel = (Button) this.findViewById(R.id.favorites_cancel);

		done.setOnClickListener(this);
		done.setEnabled(false);
		cancel.setOnClickListener(this);

		db = new DbAdapter(this);
		if (!db.isOpened)
			db.open();

		c = db.AllNotifications();
		la = new ListAdapter(this, c, AppConstants.FAVORITES);
		setListAdapter(la);
		db.close();
		// View the table in a list view
		lv = getListView();

		// Set the onClick listener for the list items
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				itemClick(v, pos, id);
			}

		});

		initializeSearchBar();

		// Set the onLongClick listener for the list items
		registerForContextMenu(lv);
		lv.setTextFilterEnabled(true);
	}

	/**
	 * Initializes the Search bar by setting the onTextChanged listeners
	 * 
	 * @author Aya Kamel
	 */
	private void initializeSearchBar() {
		EditText searching = (EditText) findViewById(R.id.searchField);
		searching.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				// After text settles fetch all contacts whose names
				// contain the string typed in the search box
				if (!db.isOpened)
					db.open();
				Cursor cursor;
				if (arg0 != null && !arg0.toString().equals(""))
					cursor = db.AllNotifications(arg0.toString());
				else
					cursor = db.AllNotifications();
				la.changeCursor(cursor);
				db.close();
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * @author Aya Kamel
	 * @param v
	 *            The view of the selected item
	 * @param pos
	 *            The id of the selected item
	 */
	private void itemClick(View v, int pos, long id) {
		if (v != null) {
			TextView info1 = (TextView) v.findViewById(R.id.info1);
			TextView info2 = (TextView) v.findViewById(R.id.info2);
			int stub_visibility = info1.getVisibility();
			if (stub_visibility == View.GONE) // invisibile
			{
				la.setExpanded(pos, true);
				info1.setVisibility(View.VISIBLE);
				info2.setVisibility(View.VISIBLE);
			} else {
				la.setExpanded(pos, false);
				info1.setVisibility(View.GONE);
				info2.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu,
	 *      android.view.View, android.view.ContextMenu.ContextMenuInfo) The
	 *      long press menu creator
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

		// Set menu look-and-feel parameters
		menu.setHeaderTitle("Options");
		menu.setHeaderIcon(R.drawable.settings);
		menu.add(0, AppConstants.MENU_DELETE, 0,
				getString(R.string.remove_favorite));

		// TO BE LOCALIZED
		if (info.id == la.cur_sel)
			menu.add(0, AppConstants.MENU_DESELECT, 0, "Deselect");
		else
			menu.add(0, AppConstants.MENU_SELECT, 0, "Select");
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 *      The onClick function for the menu items
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		// Save the request on which the current selection will take place
		final AdapterContextMenuInfo req = (AdapterContextMenuInfo) item
				.getMenuInfo();
		if (!db.isOpened)
			db.open();
		switch (item.getItemId()) {
		// Create a new notification -- will direct to another list
		case AppConstants.MENU_DELETE:
			db.deleteNotification(req.id);
			if (la.cur_sel == req.id) {
				la.cur_sel = -1;
				done.setEnabled(false);
			}
			la.remove(req.position);
			Cursor c1 = db.AllNotifications();
			la.changeCursor(c1);
			break;
		case AppConstants.MENU_SELECT:
			done.setEnabled(true);
			la.cur_sel = req.id;
			la.notifyDataSetChanged();
			break;
		case AppConstants.MENU_DESELECT:
			la.cur_sel = -1;
			done.setEnabled(false);
			la.notifyDataSetChanged();
			break;
		}
		db.close();
		return false;
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		db.close();
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!db.isOpened)
			db.open();
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	/**
	 * Sends the selected data to the corresponding activity
	 * @author Aya Kamel, Loai
	 */
	@Override
	public void finalize() {
		if (la.cur_sel != -1) {
			if (!db.isOpened) {
				db.open();
			}
			Cursor c = db.NotificationID(la.cur_sel);
			db.close();
			Intent i = new Intent();
			if (c != null) {
				// If no problems occur, pass the object to the other activity				
				 i.putExtra(AppConstants.CNAME,
				 	c.getString(c.getColumnIndex(AppConstants.CNAME)));
				 i.putExtra(AppConstants.CPHONE,
				 	c.getString(c.getColumnIndex(AppConstants.CPHONE)));
				 i.putExtra(AppConstants.LOCATION,
				 	c.getString(c.getColumnIndex(AppConstants.LOCATION)));
				 i.putExtra(AppConstants.VALUE,
				 	c.getString(c.getColumnIndex(AppConstants.VALUE)));
				 i.putExtra(AppConstants.TYPE,
				 	c.getString(c.getColumnIndex(AppConstants.TYPE)));
				 

				int tab = c.getInt(c.getColumnIndex(AppConstants.NOT_TYPE));
				switch (tab) {
				case AppConstants.TAB_INCOMING:
					i.setClass(getApplicationContext(), CreateRequest.class);
					break;
				case AppConstants.TAB_OUTGOING:
					i.setClass(getApplicationContext(), CreateOffer.class);
					break;
				default:
					i.setClass(getApplicationContext(), CreateAlarm.class);
					break;
				}
				startActivity(i);
			} else
				finish();
		} else
			finish();
	}

	/**
	 * Captures the clicks of the buttons and chooses the right action according
	 * to the clicked button
	 * 
	 * @author Aya Kamel
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == done)
			finalize();
		if (v == cancel)
			finish();
	}

}
